﻿using System;
using System.Web;

namespace Fuse8.ContentManagementFramework.Web.Etc
{
    [Flags]
    public enum BrowserType
    {
        Desktop = 0,
        Mobile = 1,
        IE = 2,
        Firefox = 3,
        Opera = 4,
        Chrome = 5,
        Safari = 6,
        Iphone = 7,
        Ipad = 8,
        Android = 9,
        Blackberry = 10
    }

    public static class UserAgentChecker
    {
        public static BrowserType DetectAgent(this HttpContext context)
        {
            BrowserType result = BrowserType.Desktop;

            if ((context != null) && (context.Request != null) && !string.IsNullOrEmpty(context.Request.UserAgent))
            {
                string userAgent = context.Request.UserAgent;
                if (UserAgentIs(userAgent, "Iphone") || UserAgentIs(userAgent, "Ipod"))
                {
                    result = BrowserType.Iphone | BrowserType.Mobile;
                }
                else if (UserAgentIs(userAgent, "Ipad"))
                {
                    result = BrowserType.Ipad | BrowserType.Mobile;
                }
                else if (UserAgentIs(userAgent, "Firefox"))
                {
                    result = BrowserType.Firefox | BrowserType.Desktop;
                }
            }

            return result;
        }

        private static bool UserAgentIs(string userAgent, string userAgentToTest)
        {
            return (userAgent.IndexOf(userAgentToTest, StringComparison.OrdinalIgnoreCase) > 0);
        }
    }
}
